/**
 * Affichage du top UGPN.
 */ 
function displayTable() {
	
	Ext.QuickTips.init();
	 
	var product		= $('#productId').get(0).value;
	var source 		= $('#sourceId').get(0).value; 
	var periode		= $('#periodId').get(0).value;
	var unite		= $('#unitId').get(0).value;
	
	$('#grid').empty(); 
	
	var itemsParPage = 23;  
	
	// Donnees JSON 
	var store = Ext.create('Ext.data.Store', {
       id:'gridUGPNStore',
       autoLoad: true,
       fields:['codeUgp', 'ugpn', 'pmCm3', 'pmCm3Icon', 'pmCm3Delta', 'pm', 'pmIcon', 'pmDelta'],
       pageSize: 1, 
       remoteSort: true,
       proxy: new Ext.data.HttpProxy({
           type: 'ajax',
           url: './grid.do?itemsParPage=' + itemsParPage + '&product=' + product + '&source=' + source + '&periode=' + periode + "&unite=" + unite + "&nivGeog=" + globalNivGeog + "&geog=" + encodeURIComponent(globalGeog) + "&idGeog=" + idGeog + "&limit=" + itemsParPage,   
           
           //url: 'https://localhost:8443/SalesReportV2/grid.do?itemsParPage=' + itemsParPage + '&product=' + product + '&source=' + source + '&periode=' + periode + "&unite=" + unite + "&nivGeog=" + globalNivGeog + "&geog=" + encodeURIComponent(globalGeog) + "&idGeog=" + idGeog + "&limit=" + itemsParPage,   
           //url: './grid.do',

           reader: {
               type: 'json',
               root: 'result.data',
               totalProperty: 'result.total'
           }
       })
	});
	
//	store.load({
//       params:{
//    	   action:'read',
//           start:0,    
//           limit: itemsParPage
////           ,
////           itemsParPage: itemsParPage,
////    	   product: product,
////    	   source: source,
////    	   periode: periode,
////    	   unite: unite,
////    	   nivGeog: globalNivGeog,
////    	   geog: globalGeog,
////    	   idGeog: idGeog
//       }
//	});
	
	var filters = {
        ftype: 'filters',
        encode: true,
        local: false,   
        filters: [{
            type: 'boolean',
            dataIndex: 'visible'
        }]
    };
	
	// Formatter de colonnes avec icones
	function formatterIcon(value) {
		var v = value + "";
		if (value == '') {
			return '';
		} else if (value >= 0) {
			return v + "&nbsp;&nbsp;<img src='img/cercle-vert.png' style='padding-right:5px;' />";
		} else if (value < -0.5) {
			return v + "&nbsp;&nbsp;<img src='img/cercle-rouge.png' style='padding-right:5px;' />";
		} else {
			return v + "&nbsp;&nbsp;<img src='img/cercle-jaune.png' style='padding-right:5px;' />";
		}
    }
	
    // Creation de la Grid 
	Ext.create('Ext.grid.Panel', { 
		viewConfig: {
			loadMask: false // permet de ne pas afficher l icone de chargement 
		},
		store: store,
		dockedItems: [{
           xtype: 'pagingtoolbar', 
           store: store,  
           dock: 'bottom'
	    }],
		columns: [
		    
		    {header: 'Code UGP',		width: '0%',	dataIndex: 'codeUgp', 		hidden:true,		hideable: false},
		    
			{header: 'UGPN',			width: '60%',	dataIndex: 'ugpn', 			sortable: true,		filterable:true},
			
			{
			    text : 'CM3',
			    width: '20%',
			    sortable:true,
			    columns: [
					{header: 'PM', 				dataIndex: 'pmCm3',			align: 'right', filterable:false, sortable:true},
					{header: '&Delta;PM', 		dataIndex: 'pmCm3Delta',	align: 'right', filterable:false, sortable:true,
						renderer: function(value) {
							return formatterIcon(value);
						}
					}
				]
		    },
		    
		    {
			    text : 'Mois',
			    width: '20%',
			    sortable:true,
			    columns: [
					{header: 'PM',				dataIndex: 'pm', 			align: 'right', filterable:false, sortable:true},
					{header: '&Delta;PM',		dataIndex: 'pmDelta', 		align: 'right', filterable:false, sortable:true,
						renderer: function(value) {
							return formatterIcon(value);
						}
					}
				]
		    }
	
		],
        features: [filters],
		stripeRows: true, 
		renderTo: 'grid',
		title:'<div style="float:left;">Top UGPN sur ' + globalGeog + '</div><div style="float:right;"><a href="#" onclick="javascript:downloadExcelTopUgpn();"><img src="img/excel-petit.png" /></a><a href="#" onclick="javascript:downloadPdfTopUgpn();"><img src="img/pdf-petit.png" /></a></div>',
		listeners : {
			cellclick : function(grid, rowIndex, cellIndex, e){  
				if (e != undefined && e.data != undefined && e.data.codeUgp != undefined) {
					loadGrid(e.data.codeUgp);
					ugpnGlobal = e.data.ugpn;
				}
			}
//			,
//			viewready: function(){
//				$('#loadGridImg').css("display", "none");
//            }
		}
	});
	
	//store.loadPage(1);
	
}

/**
 * Affichage de la liste des medecins.
 */     
function displayTableDoctors(lines) {
	
	$('#grid').empty(); 
	
	// Donnees JSON 
	var linesStore = new Ext.data.JsonStore({   
      fields: [ 'name', 'firstname', 'zipCode', 'city', 'spe', 'cible', 'nbCalls', 'dernVis', 'proVis'],
      data: lines
    });  
	
	// Filtre 
	var filters = {
        ftype: 'filters',
        encode: false,
        local: true,   
        filters: [{
            type: 'boolean',
            dataIndex: 'visible'
        }]
    };
	
    // Creation de la Grid 
	Ext.create('Ext.grid.Panel', { 
		store: linesStore,
		columns: [
			{header: 'Nom',						width: '11%', dataIndex: 'name', 		sortable: true, align: 'left', filterable:true},
			{header: 'Pr&eacute;nom',			width: '11%', dataIndex: 'firstname',	sortable: true, align: 'left', filterable:true},
			{header: 'Code postal',				width: '11%', dataIndex: 'zipCode',		sortable: true, align: 'left', filterable:true},
			{header: 'Ville',					width: '11%', dataIndex: 'city', 		sortable: true, align: 'left', filterable:true},
			{header: 'Sp&eacute;.',				width: '11%', dataIndex: 'spe', 		sortable: true, align: 'left', filterable:true},
			{header: 'Cible',					width: '11%', dataIndex: 'cible', 		sortable: true, align: 'left', filterable:true},
			{header: 'Nb calls/obj',			width: '11%', dataIndex: 'nbCalls', 	sortable: true, align: 'left', filterable:true},
			{header: 'Derni&egrave;re vis.',	width: '11%', dataIndex: 'dernVis',		sortable: true, align: 'left', filterable:true},
			{header: 'Prochaine vis.',			width: '11%', dataIndex: 'proVis', 		sortable: true, align: 'left', filterable:true}
		],
		features: [filters],
		stripeRows: true, 
		renderTo: 'grid',
		title:'<div style="float:left;">Liste des m&eacute;decins pour ' + ugpnGlobal + '</div><div style="float:right;"><a href="#" onclick="javascript:downloadExcelDoctors();"><img src="img/excel-petit.png" /></a><a href="#" onclick="javascript:downloadPdfDoctors();"><img src="img/pdf-petit.png" /></a></div>',
		listeners : {
			cellclick : function(grid, rowIndex, cellIndex, e) {  
				globalCodeUGP = "";
				loadGrid("");
			}
//			,
//			viewready: function(){
//				$('#loadGridImg').css("display", "none");
//            }
		}
	});
}

/**
 * Chargement des données JSON pour l'affichage de la grid Top UGPN ou medecins.
 */
function loadGrid(codeUgp) {
	
	$('#grid').html('<img src="img/ajax-loader.gif" style="padding-right:5px;" />'); 
	
	globalCodeUGP = codeUgp;
	
	var product    = $('#productId').get(0).value;
	var source = $('#sourceId').get(0).value; 
	var periode = $('#periodId').get(0).value;
	var unite = $('#unitId').get(0).value;
	
	// Settings activité 
	var cs_division		= $('#activite-equipe-id').get(0).value; 
	var periodeActivite = $('#activite-periode-id').get(0).value;
	var specialite		= $('#activite-specialite-id').get(0).value;
	
	if (codeUgp == "") { // Top UGPN
		displayTable();
	} else { // Medecins 
		$.ajax({ 
	 		traditional: true, 
	 		type: 'POST', 
	 		url: './grid.do',
	 		target: "_blank", 
	 		data : {
	 			product:    product,
	 			periode:    periode,
	 			source: 	source,
	 			codeUgp:    codeUgp,
	 			nivGeog:    globalNivGeog,
				geog:       globalGeog,
				idGeog: 	idGeog,
				unite:		unite,
				cs_division:		cs_division,
	 			periodeActivite:	periodeActivite,
	 			specialite:			specialite,
	 			segments:			allSegments
	 		}, 
	 		error: function () {},
	 		success: function(result) { 
	 			displayTableDoctors(result.lines);
	 		}
	 	});
	}
}